package com.sl.au.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.AfterSaleReturnVisit;
import com.sl.au.entity.Attachment;
import com.sl.au.entity.InventoryDull;
import com.sl.au.entity.InventoryReduce;
import com.sl.au.entity.Module;
import com.sl.au.entity.Option;
import com.sl.au.entity.QuoteDevice;
import com.sl.au.entity.QuoteForeign;
import com.sl.au.entity.QuoteReplacement;
import com.sl.au.entity.User;
import com.sl.au.service.ActivitiService;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.AuditNodeService;
import com.sl.au.service.InventoryDullService;
import com.sl.au.service.InventoryReduceService;
import com.sl.au.service.OptionService;
import com.sl.au.service.QuoteForeignService;

@RestController
@RequestMapping(value = "/ui/quote-foreign")
public class QuoteForeignController extends BaseController {

	@Autowired
	QuoteForeignService quoteForeignService;
	@Autowired
	OptionService optionService;
	@Autowired
	InventoryReduceService inventoryReduceService;
	@Autowired
	InventoryDullService inventoryDullService;
	@Autowired
	AttachmentService attachmentService;
	@Autowired
	ActivitiService activitiService;
	@Autowired
	AuditNodeService auditNodeService;

	// 外贸将价格单主页面
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		String name = "quoteForeign";
		Module module = this.getPageModule(name);
		ModelAndView modelAndView = createLayoutView("quoteForeign/quoteForeignindex");
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String role = a.getRole().getName();
		
		modelAndView.addObject("userId", userId);
		modelAndView.addObject("role", role);
		modelAndView.addObject("module", module);
		return modelAndView;
	}

	// 增加外贸价格单页面
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public ModelAndView addindex() {
		ModelAndView modelAndView = createLayoutView("quoteForeign/quoteForeignAdd");
		List<Option> currencies = optionService.getRepository().findByGroup("产品价格币种");
		List<Option> exportWays = optionService.getRepository().findByGroup("出口方式");
		Account a = this.getMyAccount();
		User user = a.getUser();
		modelAndView.addObject("user", user);
		modelAndView.addObject("currencies", currencies);
		modelAndView.addObject("exportWays", exportWays);
		return modelAndView;
	}

	// 编辑外贸价格单页面
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public ModelAndView editindex() {
		ModelAndView modelAndView = createLayoutView("quoteForeign/quoteForeignEdit");
		String quoteForeignId = request.getParameter("quoteForeignId");
		QuoteForeign quoteForeign = new QuoteForeign();
		if (quoteForeignId != null) {
			quoteForeign = quoteForeignService.getRepository().findOne(quoteForeignId);
		}
		List<Option> currencies = optionService.getRepository().findByGroup("产品价格币种");
		List<Option> exportWays = optionService.getRepository().findByGroup("出口方式");
		Account a = this.getMyAccount();
		User user = a.getUser();
		modelAndView.addObject("user", user);
		modelAndView.addObject("currencies", currencies);
		modelAndView.addObject("exportWays", exportWays);
		modelAndView.addObject("quote", quoteForeign);
		return modelAndView;
	}

	/**
	 * 生成外贸报价单
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/gen-quoteForeign-list/{quoteForeignId}", method = RequestMethod.GET)
	public ResponseEntity<Resource> exportWordData(@PathVariable String quoteForeignId) throws IOException {
		String filename =  quoteForeignService.genQuoteForeignDocx(quoteForeignId);
		Resource file = null;
		String shortName = "外贸报价单.docx";
		if (null != filename) {
			file = attachmentService.loadAsResource(filename);
			String url = file.getURL().toString();
			int a = url.lastIndexOf('/');
			shortName = url.substring(a + 1);
		}
		return ResponseEntity.ok()
				.header(HttpHeaders.CONTENT_DISPOSITION,
						"attachment; charset=UTF-8;filename=\"" + java.net.URLEncoder.encode(shortName, "UTF-8") + "\"")
				.body(file);
	}
	// 外贸价格单详情页面
	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	public ModelAndView detailindex() {
		ModelAndView modelAndView = createLayoutView("quoteForeign/quoteForeignDetail");
		String quoteForeignId = request.getParameter("quoteForeignId");
		QuoteForeign quoteForeign = new QuoteForeign();
		if (quoteForeignId != null) {
			quoteForeign = quoteForeignService.getRepository().findOne(quoteForeignId);
		}
		modelAndView.addObject("quote", quoteForeign);
		return modelAndView;
	}

	// 删除外贸价格单
	@RequestMapping(value = "/delQuoteForeign", method = RequestMethod.GET)
	public Map<String, Object> delQuoteForeign(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<QuoteForeign> quoteForeigns = new ArrayList<QuoteForeign>();
		for (int i = 0; i < id.length; i++) {
			String quoteForeignId = id[i];
			QuoteForeign quoteForeign = new QuoteForeign();
			quoteForeign.setId(quoteForeignId);
			quoteForeigns.add(quoteForeign);
			List<Attachment> attachments = attachmentService.getRepository().findByParentId(quoteForeignId);
			attachmentService.getRepository().deleteInBatch(attachments);
			List<QuoteReplacement> quoteReplacements = quoteForeignService.getRepository()
					.findReplacementByQuoteForeignId(quoteForeignId);
			quoteForeignService.getReplacementRepository().deleteInBatch(quoteReplacements);
			List<QuoteDevice> quoteDevices = quoteForeignService.getDeviceRepository()
					.findQuoteDeviceByQuoteForeignId(quoteForeignId);
			if (quoteDevices.size() > 0) {
				for (int n = 0; n < quoteDevices.size(); n++) {
				QuoteDevice quoteDevice = quoteDevices.get(n);
				if(quoteDevice.getInventoryState()!=null){
					if(quoteDevice.getInventoryState().equals("1")){
				String quoteDeviceId = quoteDevice.getId();
				List<QuoteDevice> quoteDevice1 = quoteForeignService.getDeviceRepository().findLinkDevice(quoteDeviceId);
				quoteDevices.addAll(quoteDevice1);
				List<InventoryReduce> inventoryReduces = inventoryReduceService.getRepository()
						.findByQuoteDeviceId(quoteDeviceId);
				if (inventoryReduces.size() > 0) {
					for (int m = 0; m < inventoryReduces.size(); m++) {
						InventoryReduce inventoryReduce = inventoryReduces.get(m);
						int number = inventoryReduce.getNumber();
						String inventoryDullId = inventoryReduce.getInventoryDullId();
						InventoryDull inventoryDull = inventoryDullService.getRepository().findOne(inventoryDullId);
						int usableNum = inventoryDull.getUsableNum();
						inventoryDull.setUsableNum(usableNum + number);
						inventoryDullService.getRepository().save(inventoryDull);
					}
					inventoryReduceService.getRepository().deleteInBatch(inventoryReduces);
				}
				}
				}
			}
				quoteForeignService.getDeviceRepository().deleteInBatch(quoteDevices);
			}
		}
		quoteForeignService.getRepository().deleteInBatch(quoteForeigns);
		map.put("code", 0);
		return map;
	}
	// 获得外贸价格单的列表
	@RequestMapping(value = "/getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String auditState = request.getParameter("auditState");//审核状态
		String name = "quoteForeign";
		Module module = this.getPageModule(name);
		String dataFilter = module.getDataFilter();
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String superior = a.getUser().getSaleArea().getSuperior();
		String areaId = a.getUser().getSaleArea().getId();
		Map<String, String> condition = new HashMap<String, String>();
		condition.put("auditState", auditState);
		condition.put("key", key);
		condition.put("dataFilter", dataFilter);
		condition.put("superior", superior);
		condition.put("areaId", areaId);
		condition.put("userId", userId);
		List<QuoteForeign> quoteForeigns = quoteForeignService.getQuoteForeign(start, length, condition, null, null);
		List<QuoteForeign> newQuoteForeigns =new ArrayList<QuoteForeign>();
		long count = quoteForeignService.getQuoteForeignCount(condition);
		for (QuoteForeign r : quoteForeigns) {
			String parentId = r.getId();
			List<Attachment> c = attachmentService.getRepository().findByParentId(parentId);
			int num = c.size();
			r.setAttachNumber(num);
			newQuoteForeigns.add(r);
		}
		map.put("data", newQuoteForeigns);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	// 获得泵明细table列表
	@RequestMapping(value = "/getMainpage", method = RequestMethod.GET)
	public Map<String, Object> getMainPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String quoteForeignId = request.getParameter("quoteForeignId");
		List<QuoteDevice> quoteDevices = quoteForeignService.getQuoteDevice(start, length, quoteForeignId, null, null);
		long count = quoteForeignService.getDeviceRepository().findQuoteDeviceCount(quoteForeignId);
		map.put("data", quoteDevices);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	// 获得其他明细table列表
	@RequestMapping(value = "/getOtherpage", method = RequestMethod.GET)
	public Map<String, Object> getOtherPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String quoteForeignId = request.getParameter("quoteForeignId");
		List<QuoteReplacement> quoteReplacements = quoteForeignService.getQuoteReplacement(start, length,
				quoteForeignId, null, null);
		long count = quoteForeignService.getRepository().getReplacementCount(quoteForeignId);
		map.put("data", quoteReplacements);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	// 得到当前设备信息数据
	@RequestMapping(value = "/getnowDatapage", method = RequestMethod.GET)
	public Map<String, Object> getnowDataPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String nowDataId = request.getParameter("nowDataId");
		Long count = null;
		List<QuoteDevice> quoteDevices = quoteForeignService.getNowQuoteDevice(start, length, nowDataId, null, null);
		count = quoteForeignService.getDeviceRepository().getNowDeviceCount(nowDataId);
		map.put("data", quoteDevices);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	// 复制新增页面
	@RequestMapping(value = "/pasteAdd", method = RequestMethod.GET)
	public ModelAndView addQuote() {
		ModelAndView modelAndView = createLayoutView("quoteForeign/quoteForeignEdit");
		String quoteForeignId = request.getParameter("quoteForeignId");
		Account a = this.getMyAccount();
		User user = a.getUser();
		if (quoteForeignId != null) {
			QuoteForeign quoteForeign = quoteForeignService.getRepository().findOne(quoteForeignId);
			modelAndView.addObject("quote", quoteForeign);
		}
		List<Option> currencies = optionService.getRepository().findByGroup("产品价格币种");
		List<Option> exportWays = optionService.getRepository().findByGroup("出口方式");
		modelAndView.addObject("user", user);
		modelAndView.addObject("currencies", currencies);
		modelAndView.addObject("exportWays", exportWays);
		return modelAndView;
	}

	// 报价审批页面
	@RequestMapping(value = "/audit/{id}", method = RequestMethod.GET)
	public ModelAndView approve(@PathVariable String id) {
		ModelAndView modelAndView = createLayoutView("quoteForeign/quote-foreign-audit");
		if (id != null) {
			QuoteForeign quoteForeign = quoteForeignService.getRepository().findOne(id);
			modelAndView.addObject("quote", quoteForeign);
			modelAndView.addObject("quoteForeignName", quoteForeign.getName());
			modelAndView.addObject("quoteForeignId", quoteForeign.getId());
		}
		return modelAndView;

	}

	// 报价审批者页面
	@RequestMapping(value = "/audit-view/{taskId}/{id}", method = RequestMethod.GET)
	public ModelAndView auditorView(@PathVariable String taskId, @PathVariable String id) {
		ModelAndView modelAndView = createLayoutView("quoteForeign/quote-foreign-audit-view");
		if (id != null && taskId != null) {
			QuoteForeign quoteForeign = quoteForeignService.getRepository().findOne(id);
			modelAndView.addObject("quote", quoteForeign);
			modelAndView.addObject("quoteForeignName", quoteForeign.getName());
			modelAndView.addObject("quoteForeignId", quoteForeign.getId());
			modelAndView.addObject("taskId", taskId);
			modelAndView.addObject("auditnodes", auditNodeService.getRepository().getNodesById(quoteForeign.getProcessInstId(),id));
		}
		return modelAndView;

	}

	// 报价审批者页面JSON
	@RequestMapping(value = "/audit-view/{taskId}/{id}/json", method = RequestMethod.GET)
	public Map<String, Object> auditorViewJSON(@PathVariable String taskId, @PathVariable String id) {
		Map<String, Object> map = new HashMap<>();
		if (id != null && taskId != null) {
			QuoteForeign quoteForeign = quoteForeignService.getRepository().findOne(id);
			List<QuoteDevice> quoteDevices = quoteForeignService.getQuoteDevice(0, Integer.MAX_VALUE, id, null, null);
			List<QuoteReplacement> quoteReplacements = quoteForeignService.getRepository()
					.findReplacementByQuoteForeignId(id);
			
			map.put("pumps", quoteDevices);
			map.put("others", quoteReplacements);
			map.put("quote", quoteForeign);
			map.put("taskId", taskId);
			map.put("auditNodes", auditNodeService.getAll(quoteForeign.getProcessInstId(),id));
		}
		return map;

	}

	// 保存价格单
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Map<String, Object> saveForeignTradeQuote(HttpServletRequest request,
			@RequestBody QuoteForeign quoteForeign) {
		Map<String, Object> map = new HashMap<String, Object>();
		quoteForeignService.getRepository().save(quoteForeign);
		String quoteId = quoteForeign.getId();
		Date createTime = quoteForeign.getCreateTime();
		map.put("code", 0);
		map.put("quoteForeignId", quoteId);
		map.put("createTime", createTime);
		return map;
	}

	// 保存泵设备
	@RequestMapping(value = "/saveMainDevice", method = RequestMethod.POST)
	public Map<String, Object> saveMain(HttpServletRequest request, @RequestBody QuoteDevice quoteDevice) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(quoteDevice.getInventoryState()!=null){
			if(quoteDevice.getInventoryState().equals("1")){
			List<InventoryReduce> inventoryReduces = inventoryReduceService.getRepository().findByQuoteDeviceId(quoteDevice.getId());
			InventoryReduce inventoryReduce = inventoryReduces.get(0);
			int number = inventoryReduce.getNumber();
			String inventoryDullId = inventoryReduce.getInventoryDullId();
			InventoryDull inventoryDull = inventoryDullService.getRepository().findOne(inventoryDullId);
			int usableNum = inventoryDull.getUsableNum();
			inventoryDull.setUsableNum(usableNum+number);
			inventoryDullService.getRepository().save(inventoryDull);
			inventoryReduceService.getRepository().delete(inventoryReduce);
			List<QuoteDevice> linkDevices = quoteForeignService.getDeviceRepository().findLinkDevice(quoteDevice.getId());
			quoteForeignService.getDeviceRepository().deleteInBatch(linkDevices);	
			quoteDevice.setInventoryState("0");
		}                
		}
		quoteForeignService.getDeviceRepository().save(quoteDevice);
		map.put("nowData", quoteDevice);
		map.put("code", 0);
		return map;
	}

	// 保存其他
	@RequestMapping(value = "/saveOtherDevice", method = RequestMethod.POST)
	public Map<String, Object> saveOther(HttpServletRequest request, @RequestBody QuoteReplacement quoteReplacement) {
		Map<String, Object> map = new HashMap<String, Object>();
		quoteForeignService.getReplacementRepository().save(quoteReplacement);
		map.put("code", 0);
		return map;
	}

	// 保存复制新增数据
	@RequestMapping(value = "/savePasteAdd", method = RequestMethod.GET)
	public Map<String, Object> savePasteAdd(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String quoteForeignId = request.getParameter("quoteForeignId");
		Account a = this.getMyAccount();
		User user = a.getUser();
		if (quoteForeignId != null) {
			QuoteForeign quoteForeign = quoteForeignService.getRepository().findOne(quoteForeignId);
			QuoteForeign newQuoteForeign = new QuoteForeign();
			newQuoteForeign.setName(quoteForeign.getName());
			newQuoteForeign.setMemo(quoteForeign.getMemo());
			newQuoteForeign.setDeliveryDate(quoteForeign.getDeliveryDate());
			newQuoteForeign.setCustomerName(quoteForeign.getCustomerName());
			newQuoteForeign.setExportWay(quoteForeign.getExportWay());
			newQuoteForeign.setCurrency(quoteForeign.getCurrency());
			newQuoteForeign.setProductSum(quoteForeign.getProductSum());
			newQuoteForeign.setProductRatio(quoteForeign.getProductRatio());
			newQuoteForeign.setProductOff(quoteForeign.getProductOff());
			newQuoteForeign.setPackPrice(quoteForeign.getPackPrice());
			newQuoteForeign.setPackRatio(quoteForeign.getPackRatio());
			newQuoteForeign.setPackOff(quoteForeign.getPackOff());
			newQuoteForeign.setSum(quoteForeign.getSum());
			newQuoteForeign.setAuditState("未提交");
			newQuoteForeign.setUser(user);
			quoteForeignService.getRepository().save(newQuoteForeign);
			map.put("quoteForeignId", newQuoteForeign.getId());
			List<QuoteDevice> quoteDevices = quoteForeignService.getDeviceRepository()
					.findQuoteDeviceByQuoteForeignId(quoteForeignId);
			List<QuoteDevice> newQuoteDevices = new ArrayList<QuoteDevice>();
			for (int i = 0; i < quoteDevices.size(); i++) {
				QuoteDevice quoteDevice = quoteDevices.get(i);
				QuoteDevice newQuoteDevice = new QuoteDevice();
				newQuoteDevice.setProductName(quoteDevice.getProductName());
				newQuoteDevice.setProductModel(quoteDevice.getProductModel());
				newQuoteDevice.setProductType(quoteDevice.getProductType());
				newQuoteDevice.setInventoryState("0");
				newQuoteDevice.setNumber(quoteDevice.getNumber());
				newQuoteDevice.setUnitPrice(quoteDevice.getUnitPrice());
				newQuoteDevice.setCostPrice(quoteDevice.getCostPrice());
				newQuoteDevice.setPower(quoteDevice.getPower());
				newQuoteDevice.setFlowMaterial(quoteDevice.getFlowMaterial());
				newQuoteDevice.setTransMedia(quoteDevice.getTransMedia());
				newQuoteDevice.setFlux(quoteDevice.getFlux());
				newQuoteDevice.setViscosity(quoteDevice.getViscosity());
				newQuoteDevice.setPumpLift(quoteDevice.getPumpLift());
				newQuoteDevice.setTemperature(quoteDevice.getTemperature());
				newQuoteDevice.setProportion(quoteDevice.getProportion());
				newQuoteDevice.setInPressure(quoteDevice.getInPressure());
				newQuoteDevice.setEffectiveNPSHA(quoteDevice.getEffectiveNPSHA());
				newQuoteDevice.setMustMPSHA(quoteDevice.getMustMPSHA());
				newQuoteDevice.setQuoteForeign(newQuoteForeign);
				newQuoteDevices.add(newQuoteDevice);
			}
			quoteForeignService.getDeviceRepository().save(newQuoteDevices);
			List<QuoteReplacement> quoteReplacements = quoteForeignService.getRepository()
					.findReplacementByQuoteForeignId(quoteForeignId);
			List<QuoteReplacement> newReplacements = new ArrayList<QuoteReplacement>();
			for (int n = 0; n < quoteReplacements.size(); n++) {
				QuoteReplacement quoteReplacement = quoteReplacements.get(n);
				QuoteReplacement newReplacement = new QuoteReplacement();
				newReplacement.setDeviceName(quoteReplacement.getDeviceName());
				newReplacement.setAmount(quoteReplacement.getAmount());
				newReplacement.setType(quoteReplacement.getType());
				newReplacement.setMaterial(quoteReplacement.getMaterial());
				newReplacement.setUnit(quoteReplacement.getUnit());
				newReplacement.setPrice(quoteReplacement.getPrice());
				newReplacement.setCostPrice(quoteReplacement.getCostPrice());
				newReplacement.setQuoteForeign(newQuoteForeign);
				newReplacements.add(newReplacement);
			}
			quoteForeignService.getReplacementRepository().save(newReplacements);
		}
		return map;
	}

	// 删除泵 设备细目，quoteDevice
	@RequestMapping(value = "/delMainDevice", method = RequestMethod.GET)
	public Map<String, Object> delMainDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<QuoteDevice> quoteDevices = new ArrayList<QuoteDevice>();
		for (int i = 0; i < id.length; i++) {
			String quoteDeviceId = id[i];
			QuoteDevice quoteDevice = quoteForeignService.getDeviceRepository().findOne(quoteDeviceId);
			if(quoteDevice.getLinkDeviceId()!=null){
				QuoteDevice quoteDevice1 = quoteForeignService.getDeviceRepository().findOne(quoteDevice.getLinkDeviceId());
				quoteDevices.add(quoteDevice1);
				List<QuoteDevice> quoteDevices1 = quoteForeignService.getDeviceRepository().findLinkDevice(quoteDevice.getLinkDeviceId());
				quoteDevices.addAll(quoteDevices1);
				List<InventoryReduce> inventoryReduces = inventoryReduceService.getRepository()
						.findByQuoteDeviceId(quoteDevice.getLinkDeviceId());
				if (inventoryReduces.size() > 0) {	
						InventoryReduce inventoryReduce = inventoryReduces.get(0);
						int number = inventoryReduce.getNumber();
						String inventoryDullId = inventoryReduce.getInventoryDullId();
						InventoryDull inventoryDull = inventoryDullService.getRepository().findOne(inventoryDullId);
						if (inventoryDull != null) {
							int usableNum = inventoryDull.getUsableNum();
							inventoryDull.setUsableNum(usableNum + number);
							inventoryDullService.getRepository().save(inventoryDull);
						}	
					inventoryReduceService.getRepository().deleteInBatch(inventoryReduces);
				}
			}
			else{
				quoteDevices.add(quoteDevice);
			}
			
		}
		quoteForeignService.getDeviceRepository().deleteInBatch(quoteDevices);
		map.put("code", 0);
		return map;
	}

	// 删除其他 设备细目
	@RequestMapping(value = "/delOtherDevice", method = RequestMethod.GET)
	public Map<String, Object> delOtherDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<QuoteReplacement> quoteReplacements = new ArrayList<QuoteReplacement>();
		for (int i = 0; i < id.length; i++) {
			String quoteReplacementId = id[i];
			QuoteReplacement quoteReplacement = new QuoteReplacement();
			quoteReplacement.setId(quoteReplacementId);
			quoteReplacements.add(quoteReplacement);
		}
		quoteForeignService.getReplacementRepository().deleteInBatch(quoteReplacements);
		map.put("code", 0);
		return map;
	}

	// 得到泵设备细目
	@RequestMapping(value = "/getQuoteDevice", method = RequestMethod.GET)
	public Map<String, Object> getQuoteDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String quoteForeignId = request.getParameter("id");
		List<QuoteDevice> quoteDevices = quoteForeignService.getDeviceRepository()
				.findQuoteDeviceByQuoteForeignId(quoteForeignId);
		map.put("quoteDevices", quoteDevices);
		return map;
	}

	// 得到其他设备细目
	@RequestMapping(value = "/getQuoteReplacement", method = RequestMethod.GET)
	public Map<String, Object> getQuoteReplacement(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String quoteForeignId = request.getParameter("id");
		List<QuoteReplacement> quoteReplacements = quoteForeignService.getRepository()
				.findReplacementByQuoteForeignId(quoteForeignId);
		map.put("quoteReplacements", quoteReplacements);
		return map;
	} 

	@RequestMapping(value = "/audit/{quoteForeignId}", method = RequestMethod.POST)
	public Map<String, Object> submitAudit(@PathVariable String quoteForeignId, HttpServletRequest request) {

		Map<String, Object> map = new HashMap<>();
		Map<String, String> variables = new HashMap<>();
		Account account = this.getMyAccount();
		int code = -1;

		String auditorNumber = request.getParameter("auditorNumber");
		String name = request.getParameter("name");
		String auditor1 = request.getParameter("auditor1");
		String auditor2 = request.getParameter("auditor2");
		String auditor3 = request.getParameter("auditor3");
		String auditor4 = request.getParameter("auditor4");
		String auditor5 = request.getParameter("auditor5");
		String auditor6 = request.getParameter("auditor6");
		String auditor7 = request.getParameter("auditor7");
		String auditor8 = request.getParameter("auditor8");

		if (null != quoteForeignId && null != account && null != auditorNumber) {
			// 放置流程实例变量
			variables.put("starter", account.getUser().getId());
			variables.put("auditor1", auditor1);
			variables.put("auditor2", auditor2);
			variables.put("auditor3", auditor3);
			variables.put("auditor4", auditor4);
			variables.put("auditor5", auditor5);
			variables.put("auditor6", auditor6);
			variables.put("auditor7", auditor7);
			variables.put("auditor8", auditor8);
			

			variables.put("auditorNumber", auditorNumber);
			variables.put("auditState", "已提交");
			variables.put("entityName", "quote-foreign");
			variables.put("processDefinitionName", "外贸价格单");

			variables.put("entityId", quoteForeignId);

			ProcessInstance pInst = activitiService.startProcessInstance("bid", account.getUser().getId(), variables);
			// 流程启动后，将其实例相关信息保存到业务实体中，以便查询
			quoteForeignService.saveProcessStart(quoteForeignId, pInst);
			code = 0;

		}
		map.put("code", code);
		return map;
	}
	
	// 得到价格单设备
	@RequestMapping(value = "/getEditQuoteDevice", method = RequestMethod.GET)
	public Map<String, Object> getEditQuoteDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String quoteDeviceId = request.getParameter("quoteDeviceId");
		QuoteDevice quoteDevice = quoteForeignService.getDeviceRepository().findOne(quoteDeviceId);
		map.put("quoteDevice", quoteDevice);
		return map;
	}
	
	// 获得其他明细table列表
			@RequestMapping(value = "/getOtherpageER", method = RequestMethod.GET)
			public Map<String, Object> getOtherpageER(HttpServletRequest request) {
				Map<String, Object> map = new HashMap<String, Object>();
				Map<String, String> condition = new HashMap<String, String>();
				int start = Integer.parseInt(request.getParameter("start"));
				int length = Integer.parseInt(request.getParameter("length"));
				String quoteId = request.getParameter("quoteId");
				String key = request.getParameter("key");
		        if (key == null) {
					key = "";
				}
				key = key.replaceAll("\\s+", "");
				condition.put("quoteId", quoteId);
				condition.put("key", key);
				List<QuoteReplacement> quoteReplacements = quoteForeignService.getQuoteReplacementER(start, length, condition, null, null);
				long count = quoteForeignService.getRepository().getReplacementCountER(quoteId, key);
				map.put("data", quoteReplacements);
				map.put("draw", request.getParameter("draw"));
				map.put("recordsFiltered", count);
				map.put("recordsTotal", count);
				return map;
			}
			// 获得其他明细table列表
			@RequestMapping(value = "/getOtherpageprice", method = RequestMethod.GET)
			public Map<String, Object> getOtherpageprice(HttpServletRequest request) {
				Map<String, Object> map = new HashMap<String, Object>();
				Map<String, String> condition = new HashMap<String, String>();
				int start = Integer.parseInt(request.getParameter("start"));
				int length = Integer.parseInt(request.getParameter("length"));
				String type = request.getParameter("type");
				String deviceName = request.getParameter("deviceName");
				String material = request.getParameter("material");
				if (type == null) {
					type = "";
				}
				if (deviceName == null) {
					deviceName = "";
				}
				if (material == null) {
					material = "";
				}
				condition.put("type", type);
				condition.put("deviceName", deviceName);
				condition.put("material", material);
				List<QuoteReplacement> quoteReplacements = quoteForeignService.getQuoteReplacementERprice(start, length, condition, null, null);
				long count = quoteForeignService.getRepository().getReplacementCountERprice(type, deviceName, material);
				map.put("data", quoteReplacements);
				map.put("draw", request.getParameter("draw"));
				map.put("recordsFiltered", count);
				map.put("recordsTotal", count);
				return map;
			}
	
}
